package com.jintoufs.web.action.finance;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jintoufs.dao.QueryFilters;
import com.jintoufs.dao.QueryRule;
import com.jintoufs.domain.account.AccountDetail;
import com.jintoufs.domain.account.Withdraw;
import com.jintoufs.domain.constants.Constants;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.domain.shop.Shop;
import com.jintoufs.domain.shop.ShopManager;
import com.jintoufs.domain.sys.Dictionary;
import com.jintoufs.service.account.AccountDetailService;
import com.jintoufs.service.account.WithdrawService;
import com.jintoufs.service.customer.CustomerService;
import com.jintoufs.service.shop.ShopManagerService;
import com.jintoufs.service.shop.ShopService;
import com.jintoufs.service.sys.DictionaryService;
import com.jintoufs.util.date.DateUtils;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.web.action.support.JqgridPage;
import com.jintoufs.web.action.support.SupportAction;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

@Controller
@RequestMapping("/finance")
public class FinanceAction extends SupportAction {
    @Resource
    private AccountDetailService accountDetailService;
    @Resource
    private WithdrawService withdrawService;
    @Resource
    private CustomerService customerService;
    @Resource
    private DictionaryService dictionaryService;
    @Resource
    private ShopService shopService;
    @Resource
    private ShopManagerService shopManagerService;

    @RequestMapping("/list")
    public String list() {
        return "finance/list";
    }

    @RequestMapping("/query")
    @ResponseBody
    public JqgridPage query(int page, int rows, String sidx, String sord, String filters) {
        PageHelper.startPage(page, rows);
        QueryFilters filters_;
        if (filters == null || filters.trim().isEmpty()) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        List<Map<String, Object>> list = withdrawService.getByFilter(filters_);
        // 用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(),
                pageInfo.getList());
    }

    @RequestMapping("/doWithdraw")
    @ResponseBody
    @Transactional
    public AjaxMsg doWithdraw(String id, String remark, String status) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Withdraw withdraw = withdrawService.selectById(id);
            withdraw.setStatus(status);
            withdraw.setRemark(remark);
            withdrawService.update(withdraw);
            Customer customer = null;
            Shop shop = null;
            if (!ValidUtil.isEmpty(withdraw.getCustomerId())) {
                customer = customerService.getById(withdraw.getCustomerId());
            }
            if (!ValidUtil.isEmpty(withdraw.getShopId())) {
                shop = shopService.selectById(withdraw.getShopId());
                Map map = new HashMap();
                map.put("shopId", shop.getId());
                List<Map<String, Object>> list = shopManagerService.queryByParam(map);
                if (!ValidUtil.isEmpty(list)) {
                    customer = customerService.getById(list.get(0).get("customer_id").toString());
                }
            }

            if (Constants.WITHDRAW_STATUS_ORVER.equals(status)) {

                //供应商提现结算金额
                if (!ValidUtil.isEmpty(withdraw.getShopId())) {
//                    shop.setAccount(shop.getAccount().subtract(withdraw.getPrice()));
                    shopService.save(shop,null);
                } else {
                    //分润提现,已经扣款了的，无需再次扣除
                    //customer.setDivided(customer.getDivided().subtract(withdraw.getPrice()));
                    customerService.update(customer);
                }

                AccountDetail accountDetail = new AccountDetail();
                accountDetail.setShopId(withdraw.getShopId());
                accountDetail.setCreateDate(new Date());
                accountDetail.setType(Constants.ACCOUNT_OUT);
                accountDetail.setAmountOfMoney(withdraw.getPrice().negate());
                accountDetail.setId(getUUID());
                accountDetailService.insert(accountDetail);
                List<Dictionary> list = dictionaryService.getDicByKeyNo("WITHDRAW_SUCCESS");
                if (!list.isEmpty()) {
                    int smsId = Integer.parseInt(list.get(0).getCaption().toString());
                    ArrayList<String> params = new ArrayList<>();
                    params.add(String.valueOf(withdraw.getPrice()));
                    params.add(DateUtils.formatDate(new Date(), "yyyy-MM-dd"));
                    customerService.sendSms(customer.getMobilePhone(), params, smsId);
                } else {
                    List<Dictionary> list2 = dictionaryService.getDicByKeyNo("WITHDRAW_FAIL");
                    if (!list2.isEmpty() && list2.size() > 0) {
                        int smsId = Integer.parseInt(list2.get(0).getCaption().toString());
                        ArrayList<String> params = new ArrayList<>();
                        params.add(DateUtils.formatDate(withdraw.getCreateTime(), "yyyy-MM-dd"));
                        params.add(String.valueOf(withdraw.getPrice()));
                        customerService.sendSms(customer.getMobilePhone(), params, smsId);
                    }
                }
                ajaxMsg.setCode(AjaxMsg.SUCCESS);
                ajaxMsg.setMessage("处理成功");
            }else if(Constants.WITHDRAW_STATUS_REFUSED.equals(status)){
                List<Dictionary> list2 = dictionaryService.getDicByKeyNo("WITHDRAW_FAIL");
                if (!list2.isEmpty() && list2.size() > 0) {
                    int smsId = Integer.parseInt(list2.get(0).getCaption().toString());
                    ArrayList<String> params = new ArrayList<String>();
                    params.add(DateUtils.formatDate(withdraw.getCreateTime(), "yyyy-MM-dd"));
                    params.add(String.valueOf(withdraw.getPrice()));
                    customerService.sendSms(customer.getMobilePhone(), params, smsId);
                }
                if (!ValidUtil.isEmpty(withdraw.getShopId())) {
                    shop.setAccount(shop.getAccount().add(withdraw.getPrice()));
                    shopService.save(shop,null);
                } else {
                    customer.setDivided(customer.getDivided().add(withdraw.getPrice()));
                    customerService.update(customer);
                }
                ajaxMsg.setCode(AjaxMsg.SUCCESS);
                ajaxMsg.setMessage("处理成功");
            }
        } catch (
                Exception e)

        {
            e.printStackTrace();
            ajaxMsg.setMessage("服务器错误");
            ajaxMsg.setCode(AjaxMsg.FAILURE);
        }
        return ajaxMsg;

    }

    @RequestMapping("/shop-manager-list")
    public String shopManageList() {
        return "finance/shop-manager-list";
    }

    @RequestMapping("/platform-list")
    public String platformList() {
        return "finance/platform-list";
    }

    @RequestMapping("shop-manage-query")
    @ResponseBody
    public JqgridPage shopManageQuery(int page, int rows, String sidx, String sord, String filters) {
        PageHelper.startPage(page, rows);
        QueryFilters filters_;
        if (filters == null || filters.trim().isEmpty()) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
        QueryRule queryRule;
        queryRule = new QueryRule();
        queryRule.setField("type");
        queryRule.setOp("eq");
        queryRule.setData("0");
        filters_.getRules().add(queryRule);
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        List<Customer> list = customerService.getByFilter(filters_);
        // 用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(),
                pageInfo.getList());
    }

    @RequestMapping("/platform-query")
    @ResponseBody
    public JqgridPage platformQuery(int page, int rows, String sidx, String sord, String filters) {
        PageHelper.startPage(page, rows);
        QueryFilters filters_;
        if (filters == null || filters.trim().isEmpty()) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
//        QueryRule queryRule;
//        queryRule = new QueryRule();
//        queryRule.setField("ad.type");
//        queryRule.setOp("eq");
//        queryRule.setData("0");
//        filters_.getRules().add(queryRule);
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        List<Map<String, Object>> list = accountDetailService.getPlatformByFilter(filters_);
        // 用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(),
                pageInfo.getList());
    }

}
